window.onload = function () {
  //获取上一界面传来的商品id
  function getValue(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }

  let goodId = getValue("goodsId");

  const detailEl = document.querySelector(".detail");
  const swiperWrapper = document.querySelector(".swiper-wrapper");
  const index = document.querySelector(".index");
  let sum = 0;
  const price = document.querySelector(".price");
  const goodD = document.querySelector(".goodD p");
  let goodDImg = "";
  const goodDescriptionImg = document.querySelector(".goodDescriptionImg");
  const addGoodTopRPrice = document.querySelector(".addGoodTopRPrice");
  const addGoodKc = document.querySelector(".addGoodKc");
  const hidden = document.querySelector("#hidden");
  const hidden2 = document.querySelector("#hidden2");

  axios
    .get("goods/detail", {
      params: { goodsId: goodId },
    })
    .then((res) => {
      if (res.status == 200) {
        const {
          data: {
            data: { detail },
          },
        } = res;

        //轮播图
        sum = detail.goods_images.length;
        swiperWrapper.innerHTML = detail.goods_images.map(function (
          item,
          index
        ) {
          goodDImg += `<img src="${item.external_url}">`;
          return `
            <div class="swiper-slide">
              <img src="${item.external_url}">
            </div>
          `;
        });
        let cha = document.querySelector(".swiper");
        var mySwiper = new Swiper(".swiper", {
          speed: 800,
          loop: true,
          autoplay: {
            disableOnInteraction: false,
            delay: 1000,
          },
          pagination: {
            el: ".swiper-pagination",
          },
          centeredSlides: true,
          observer: true, //修改swiper自己或子元素时，自动初始化swiper
          //observeParents: true, //修改swiper的父元素时，自动初始化swiper
          observeParents: true, //修改swiper的父元素时，自动初始化swiper
          observerUpdate: true,
          on: {
            slideChange: function () {
              index.innerHTML = `${this.realIndex + 1}/${sum}`;
            },
          },
        });

        //加入购物车
        addGoodTopRPrice.innerHTML = detail.goods_price_max;
        addGoodKc.innerHTML = `库存：${detail.stock_total}`;
        hidden.value = detail.stock_total;
        hidden2.value = detail.skuList[0].goods_sku_id;
        addGoodTopImg.src =
          "http://cba.itlike.com/public/uploads/10001/20230321/8f505c6c437fc3d4b4310b57b1567544.jpg";
        //商品详情
        price.innerHTML = `
          <p class="priceLeft">
            <span>￥</span>
            <i>${detail.goods_price_max}</i>
            <b>￥${detail.line_price_max}</b>
          </p>
          <p class="priceRight">已售${detail.goods_sales}件</p>
        `;
        goodD.innerHTML = `${detail.goods_name}`;
        goodDescriptionImg.innerHTML = goodDImg;
      } else {
        detailEl.style.display = "block";
      }
    });

  //加入购物车
  const addGood = document.querySelector(".addGood");
  const mask = document.querySelector(".mask");
  const close = document.querySelector("#closeAddCart");
  const addCart = document.querySelector(".addCart");
  const jrgwc = document.querySelector("#jrgwc");
  const buy = document.querySelector("#buy");
  const count = document.querySelector(".count");
  const input = document.querySelector("[type=text]");
  const goodNum = document.querySelector("#goodNum");
  const addGoodTopImg = document.querySelector("#addGoodTopImg");
  let val = 1;

  //界面加载获取token
  const userMsg = JSON.parse(localStorage.getItem("userMsg")) || [];

  const token = userMsg.token;

  //添加拦截器
  axios.interceptors.request.use(
    function (config) {
      //在发送请求之前做些什么
      config.headers = { "Access-Token": token, platform: "H5" };
      return config;
    },
    function (error) {
      return Promise.reject(error);
    }
  );

  //加入购物车
  const maskPrompt = document.querySelector(".maskPrompt");
  const shopCart = document.querySelector("#shopCart");
  addCart.addEventListener("click", function () {
    isToken();
    let goodsNum = goodNum.value;
    axios
      .post("cart/add", {
        goodsId: goodId,
        goodsSkuId: hidden2.value,
        goodsNum: goodsNum,
      })
      .then(({ data: res }) => {
        closeFn();

        //加入购物车成功后获取购物车商品总量
        getGoodNum();
      })
      .catch((err) => console.dir(err));
  });

  //获取购物车总量
  //初始化界面获取购物车商品总量
  getGoodNum();
  async function getGoodNum() {
    let { data: res } = await axios.get("cart/total", {
      headers: {
        "Access-Token": token,
      },
    });

    document.querySelector(".shopCartNum").innerHTML = res.data.cartTotal;
  }

  //点击购物车图标
  shopCart.addEventListener("click", isToken);

  //若没获取到token则出现弹窗（封装）
  function isToken() {
    if (token) {
      // location.href = "shopCart.html";
    } else {
      maskPrompt.style.display = "block";
    }
  }

  jrgwc.addEventListener("click", cartFun);
  buy.addEventListener("click", cartFun);

  //点击购买和加入购物车函数封装
  function cartFun() {
    const index = this.dataset.index;
    if (index == "2") {
      addCart.innerHTML = "立即购买";
      addCart.classList.add("cur");
    } else {
      addCart.classList.remove("cur");
    }
    mask.style.display = "block";
    addGood.classList.add("cur");
  }
  close.addEventListener("click", closeFn);

  function closeFn() {
    mask.style.display = "none";
    addGood.classList.remove("cur");
    input.value = 1;
  }

  //点击无理由退货
  const Asale = document.querySelector("#Asale");
  const afterSale = document.querySelector("#afterSale");
  const closeBtn = document.querySelector("#close");
  //开启
  Asale.addEventListener("click", function () {
    afterSale.classList.add("cur");
    mask.style.display = "block";
  });

  //关闭
  closeBtn.addEventListener("click", function () {
    afterSale.classList.remove("cur");
    mask.style.display = "none";
  });

  count.addEventListener("click", function (e) {
    let target = e.target;
    if (target.className == "decrease") {
      if (val == 1) {
        return alert("不能再减了~");
      } else {
        val--;
        input.value = val;
      }
    }
    if (target.className == "increase") {
      val++;
      input.value = val;
    }
  });

  //获取评论
  const lookMore = document.querySelector(".lookMore");
  async function getEvaluate() {
    let { data: res } = await axios(
      "http://cba.itlike.com/public/index.php?s=/api/comment/listRows",
      {
        params: {
          goodsId: goodId,
          limit: 3,
        },
      }
    );
    let evaluteTxt = res.data.list;

    const ul = document.querySelector(".evaluteCont ul");
    const length = evaluteTxt.length;
    document.querySelector(".goodEvaluate").innerHTML = length;

    lookMore.style.display = length == 0 ? "none" : "blcok";

    ul.innerHTML = evaluteTxt
      .map((item) => {
        const {
          content,
          create_time,
          score,
          user: { nick_name, avatar_url },
        } = item;
        let avatarUrl = avatar_url
          ? avatar_url
          : "http://cba.itlike.com/public/mweb/static/default-avatar.png";

          console.log(item)
        let str = "";
        for (let i = 0; i < score / 2; i++) {
          str += `
          <i class="iconfont icon-shoucang"></i>
        `;
        }
        let starArr = []
        starArr.push(item)
        getStarNum(str, starArr);

        return `
        <li>
          <div class="evaluteTop">
            <img
              src="${avatarUrl}"
              draggable="false"
            />
            <span>${nick_name}</span>
            <div class="star">
              ${str}
            </div>
          </div>
          <div class="evaluteDetail">
            <p class="txt">${content}</p>
            <p class="time">${create_time}</p>
          </div>
        </li>
      `;
      })
      .join("");
  }
  getEvaluate();

  //点击查看更多跳转
  lookMore.addEventListener("click", function () {
    location.href = `moreEvaluate.html?goodId=${goodId}`;
  });
};

function getStarNum(str, ele) {
  str = ele
    .map((el) => {
      if (el.score == 10) {
        return `
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
      `;
      } else if (el.score == 20) {
        return `
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
          <i class="iconfont icon-shoucang"></i>
      `;
      } else if (el.score == 30) {
        return `
          <i class="iconfont icon-shoucang"></i>
      `;
      }
    })
    .join("");
}
